package com.elf.reactnative;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class FileDownload {

    public static void download(final String url, final String saveFile, final DownloadListener listener) {
        if (new File(saveFile).exists()) {
            if (listener != null) {
                listener.success(saveFile);
            }
            return;
        }

        //下载
        new Thread() {
            @Override
            public void run() {
                try {
                    String tempFile = saveFile + ".temp";
                    downloadFile(url, tempFile);
                    if (new File(tempFile).renameTo(new File(saveFile))) {
                        if (listener != null) {
                            listener.success(saveFile);
                        }
                    } else {
                        throw new Exception("读取文件失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (listener != null) {
                        listener.fail("加载错误：" + e.getMessage());
                    }
                }
            }
        }.start();
    }

    private static void downloadFile(String url, String file) throws Exception {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            InputStream is = connection.getInputStream();

            int length = connection.getContentLength();

            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int readCount = 0, len;
            while ((len = is.read(buffer)) != -1) {
                readCount += len;
                fos.write(buffer, 0, len);
//                if (listener != null) {
//                    listener.onProgress(readCount, length);
//                }
            }
            is.close();
            fos.close();
        } else {
            throw new Exception("下载失败:" + responseCode);
        }
    }

    public interface DownloadListener {
        void success(String fileName);

        void fail(String msg);
    }
}
